import {history} from "umi";

//定义额外的路由变量
let extraRoutes

export function patchRoutes({routes}) {
    // console.log(require('@/pages/user1'));
    //动态添加路由
    routes.unshift({
        path: '/foo',
        title: "foo",
        // 不能直接写字符串,component需要的是一个组件,通过require的default获取
        component: require('@/pages/user1').default,
    });

    extraRoutes.map(item => {
        routes.unshift({
            path: item.path,
            component: require(`@/pages${item.component}`).default,
        })
    })

    // console.log(routes);

}

//复写render,会在pathRoutes之前执行
export function render(oldRender) {
    //模拟从服务器请求获得的路由
    // fetch('/api/routes').then(res=>res.json()).then((res) => {
    //     extraRoutes = res.routes;
    //     oldRender();
    // })

    extraRoutes = [
        {path: "/server", component: "/user2"}
    ]

    //渲染之前,做一些权限的校验
    const isLogin = true;
    if (!isLogin) {
        history.push("/login");
    }

    //执行渲染
    oldRender();
}

//在初始加载和路由切换时做一些事情。
export function onRouteChange({location, routes, action, matchedRoutes}) {
    //用于埋点统计
    console.log(location.pathname, '被访问了');
    // console.log(routes);
    // console.log(action);

    //设置标题
    if (matchedRoutes.length) {
        document.title = matchedRoutes[matchedRoutes.length - 1].route.title || '';
    }
}
